package com.polaris.live.utils

import android.app.Activity
import android.graphics.Color
import android.net.Uri
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.UriUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.polaris.live.common.engine.GlideEngine
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.openGalleryDefault
import com.yalantis.ucrop.UCrop
import java.io.File

/**
 * 图片裁剪工具类
 *
 * @author Created by 天晴 on 2023/12/19 20:33
 * @since 1.0.0
 */
object CropUtils {

    fun startCamera(mActivity: Activity, onResult: (result: String) -> Unit, onCancel: () -> Unit) {
        PictureSelector.create(mActivity)
            .openCamera(SelectMimeType.ofImage())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>) {
                    result.getOrNull(0)?.realPath?.let {
                        onResult.invoke(it)
                    }
                }

                override fun onCancel() {
                    onCancel.invoke()
                }
            })
    }

    fun startCameraCrop(
        mActivity: Activity,
        x: Float,
        y: Float,
        width: Int,
        height: Int,
        onResult: (result: String) -> Unit,
        onCancel: () -> Unit,
    ) {
        PictureSelector.create(mActivity)
            .openCamera(SelectMimeType.ofImage())
            .setCropEngine { fragment, currentLocalMedia, _, requestCode ->
                pictureSelectorCrop(
                    fragment = fragment,
                    sourcePath = currentLocalMedia.realPath,
                    requestCode = requestCode,
                    x = x,
                    y = y,
                    width = width,
                    height = height
                )
            }
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>) {
                    result.getOrNull(0)?.realPath?.let {
                        onResult.invoke(it)
                    }
                }

                override fun onCancel() {
                    onCancel.invoke()
                }
            })
    }

    fun startVideo(mActivity: Activity, onResult: (result: String) -> Unit, onCancel: () -> Unit) {
        PictureSelector.create(mActivity)
            .openCamera(SelectMimeType.ofVideo())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: java.util.ArrayList<LocalMedia?>?) {
                    result?.getOrNull(0)?.realPath?.let {
                        onResult.invoke(it)
                    }
                }

                override fun onCancel() {
                    onCancel.invoke()
                }
            })
    }

    fun startAlbumNoCrop(
        mActivity: Activity,
        onResult: (result: String) -> Unit,
        onCancel: () -> Unit,
    ) {
        PictureSelector.create(mActivity)
            .openGallery(SelectMimeType.ofAll())
            .setFilterMaxFileSize(ImageUtils.MAX_SELECT_SIZE)
            .isWebp(false)
            .setMaxSelectNum(1)
            .setImageEngine(GlideEngine.createGlideEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.getOrNull(0)?.cutPath?.let {
                        val file = UriUtils.uri2File(Uri.parse(it))
                        file?.let {
                            onResult.invoke(it.absolutePath)
                        }
                    }
                }

                override fun onCancel() {
                    onCancel.invoke()
                }
            })
    }

    fun startAlbum(
        mActivity: Activity,
        onResult: (result: String) -> Unit,
        onCancel: () -> Unit,
        x: Float = 3F,
        y: Float = 5F,
        width: Int = 1080,
        height: Int = 1920,
    ) {
        PictureSelector.create(mActivity)
            .openGalleryDefault(1)
            .setCropEngine { fragment, currentLocalMedia, _, requestCode ->
                pictureSelectorCrop(
                    fragment,
                    currentLocalMedia.realPath,
                    requestCode,
                    x,
                    y,
                    width,
                    height
                )
            }
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    result?.getOrNull(0)?.cutPath?.let {
                        val file = UriUtils.uri2File(Uri.parse(it))
                        file?.let {
                            onResult.invoke(it.absolutePath)
                        }
                    }
                }

                override fun onCancel() {
                    onCancel.invoke()
                }
            })
    }

    fun startCrop(
        activity: Activity,
        sourcePath: String,
        x: Float = 3F,
        y: Float = 5F,
        width: Int = 1080,
        height: Int = 1920,
    ) {
        if (sourcePath.isEmpty()) {
            return
        }
        val file = File(sourcePath)
        if (!file.exists()) {
            return
        }
        val sourceUri: Uri = UriUtils.file2Uri(file)

        val imagesDir = File(activity.applicationContext.cacheDir, "crop_cache.jpg")
        imagesDir.createNewFile() //创建文件
        val destinationUri: Uri = UriUtils.file2Uri(imagesDir)
        val options = UCrop.Options()
        options.apply {
            setToolbarColor(Color.BLACK)
            setStatusBarColor(Color.BLACK)
            setToolbarWidgetColor(Color.WHITE)
            setActiveControlsWidgetColor(Color.parseColor("#FE1849"))
        }
        UCrop.of(sourceUri, destinationUri)
            .withOptions(options)
            .withAspectRatio(x, y)
            .withMaxResultSize(width, height)
            .start(activity)

    }

    private fun pictureSelectorCrop(
        fragment: Fragment,
        sourcePath: String,
        requestCode: Int,
        x: Float = 3F,
        y: Float = 5F,
        width: Int = 1080,
        height: Int = 1920,
    ) {
        if (sourcePath.isEmpty()) {
            return
        }
        val file = File(sourcePath)
        if (!file.exists()) {
            return
        }

        val activity = fragment.requireActivity()
        val sourceUri: Uri = UriUtils.file2Uri(file)
        val imagesDir = File(activity.applicationContext.cacheDir, "crop_cache.jpg")
        imagesDir.createNewFile() //创建文件
        val destinationUri: Uri = UriUtils.file2Uri(imagesDir)
        val options = UCrop.Options()
        options.apply {
            setToolbarColor(Color.BLACK)
            setStatusBarColor(Color.BLACK)
            setToolbarWidgetColor(Color.WHITE)
            setActiveControlsWidgetColor(Color.parseColor("#FE1849"))
        }
        UCrop.of(sourceUri, destinationUri)
            .withOptions(options)
            .withAspectRatio(x, y)
            .withMaxResultSize(width, height)
            .start(activity, fragment, requestCode)

    }

}